package cn.semyes.ylipfilter.controller.visitorIpManager;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.semyes.ylipfilter.bean.Constants;
import cn.semyes.ylipfilter.bean.User;
import cn.semyes.ylipfilter.common.util.CreateJsonObject;
import cn.semyes.ylipfilter.common.util.GetHttpJsonobject;
import cn.semyes.ylipfilter.common.util.GetRemoteApiUtils;
import cn.semyes.ylipfilter.common.util.PageUtils;
import cn.semyes.ylipfilter.common.util.R;
import cn.semyes.ylipfilter.entity.ExcludeIpEntity;
import cn.semyes.ylipfilter.service.ExceptionOneWeekIpService;
import cn.semyes.ylipfilter.service.ExcludeIpService;
import cn.semyes.ylipfilter.service.VisitorIpManagerService;



@RestController
@RequestMapping("/visitor")
public class VisitorIpManagerController {
	
	//页数
	private int page = 0;
	//最新的日期
	private String yesterday = null;
	//比较前的日期
	private String oneWeekAgo = null; 
	//页数
	private int curPage = 0;
	
	//每页开始的下标
	private int perFirst = 0;
	//总的数据
	private int num = 0;
	//list下标
	private int index = 0;
	
	private User user;
	
	private int ipOrNot = 0;
	private int addordel = 0; //前端传值过来,0:从百度ip排除列表删除; 1:添加到百度ip排除列表
	//解析json数据
	private JSONObject jsonObject = null;
	private JSONArray jsonArray = null;
	private JSONObject data = null;
	private JSONObject jsonParams = null;
	//全部的json数据
	private List<String> str = null;
	//列表数据
	private List<String> list;
	//分页组件
	private PageUtils pageUtil;
	
	private int todayIpnum = 0;
	
	private String ipArea;
	private String ip;
	
	private GetHttpJsonobject getHttpJsonobject; 
	private CreateJsonObject createJsonObject;
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private VisitorIpManagerService visitorIpManagerService;
	
	@Autowired
	private ExcludeIpService excludeIpService;
	
	private ExceptionOneWeekIpService exceptionOneWeekIpService = GetRemoteApiUtils.getRemoteService(ExceptionOneWeekIpService.class,"exceptionOneWeekIpService");
	
	@RequestMapping("/index.do")
	public ModelAndView getView() {
		ModelAndView mav = new ModelAndView("index.html");
		return mav;
	}
	
	@GetMapping("/getIpData.do")
	public R getVisitorComputer(@RequestParam Map<String, Object> params, HttpServletRequest request) {
	
		//获取请求参数
		page = Integer.parseInt(params.get("page").toString());
		yesterday = params.get("yesterday").toString();
		oneWeekAgo = params.get("oneweekago").toString();
//		logger.info("ip参数："+String.valueOf(page)+"  "+yesterday+oneWeekAgo);
		
		
        list = new ArrayList<>();
        jsonObject = new JSONObject();
        jsonArray = new JSONArray();
        
        user = new User();
        getBdUserInfo(request);
        
		if (str == null) {
			//查询列表数据
			str = exceptionOneWeekIpService.getIpAllData(user.getUserId(), yesterday, oneWeekAgo);
			
			if (str!= null) {		
				Collections.reverse(str);
				return R.ok().put("page",getIpData(str, page));
			}
			
		}
      
        pageUtil = new PageUtils(null, 0, 0, 0);
		return R.ok().put("page", pageUtil);
	}
	
	//更新百度ip排除列表
	@GetMapping("/update.do")
	public R updateIpList(@RequestParam Map<String, Object> params) {
		
		createJsonObject= new CreateJsonObject();
    	getHttpJsonobject = new GetHttpJsonobject();
    	jsonParams = new JSONObject();
    	addordel = Integer.parseInt(params.get("addordel").toString());
    	ip = params.get("excludeIp").toString();
    	if (addordel == 1) {  //1代表添加ip到百度
    		excludeIpService.saveExcludeIp(user.getUserDomain(), ip);
		} else if (addordel == 0) {  //0代表从百度删除ip
			//查找ip是否存在排除列表
			if (excludeIpOrNot(user.getUserDomain(), ip) == 1) {
				excludeIpService.deleteByDomainAndIp(user.getUserDomain(), ip);
			} else { //如果不存在直接返回0，不需更新
				return R.ok().put("data", 0);
			}
		}
    	//完成ip在本地数据库的增删操作，然后更新到百度ip排除列表
    	jsonParams.put("excludeIp", getExcludeIpList(user.getUserDomain()));
		return R.ok().put("data", updateIpList(jsonParams));
		
	}
	
	//获取当天ip数据
	@GetMapping("/getOneIp.do")
	public R getCurDayIp(@RequestParam Map<String, Object> params) {
		jsonObject = new JSONObject();
		jsonArray = new JSONArray();
		//获取请求参数
	    page = Integer.parseInt(params.get("page").toString());
	   
	    String curday = params.get("curday").toString();
//		logger.info("获取当前天来获取ip："+curday);
		
		str = exceptionOneWeekIpService.getOneIp(user.getUserId(), curday);
		
		if (str != null) {
			return R.ok().put("page",getIpData(str, page));
		}
		pageUtil = new PageUtils(null, 0, 0, 0);
		return R.ok().put("page", pageUtil);
		
			
	}
	
	
	//获取数据传输给前端生成excel
	@GetMapping("/dowloadExcel.do")
	public R getExcel(@RequestParam Map<String, Object> params) {
		
		yesterday = params.get("yesterday").toString();
		oneWeekAgo = params.get("oneweekago").toString();
		
		list = new ArrayList<>();
		jsonObject = new JSONObject();
		jsonArray = new JSONArray();
		
		
		if (str == null) {
			//查询列表数据
			str = exceptionOneWeekIpService.getIpAllData(user.getUserId(), yesterday, oneWeekAgo);
			
			if (str!= null) {
				Collections.reverse(str);
				for(index = 0; index < str.size();index++) {
					JSONObject excelJson = new  JSONObject();
					jsonObject = JSONObject.parseObject(str.get(index));
					excelJson.put("mip",jsonObject.getString("mip"));
					excelJson.put("mcount",jsonObject.getString("mcount"));
					excelJson.put("mstartTime",jsonObject.getString("mstartTime"));
					excelJson.put("mendTime",jsonObject.getString("mendTime"));
					excelJson.put("mtotalSecond",jsonObject.getString("mtotalSecond"));
					excelJson.put("miparea",exceptionOneWeekIpService.getIpLocation(jsonObject.getString("mip")));
					
					ipOrNot = excludeIpOrNot(user.getUserDomain(), jsonObject.getString("mip"));
		         	if (ipOrNot == 1) {
		         		excelJson.put("maddornot","已添加到百度ip排除列表");
					} else {
						excelJson.put("maddornot","未添加到百度ip排除列表");
					}
		 			jsonArray.add(excelJson);
				}
				
			} else {
				return R.ok().put("data", null);
			}
			str = null;
			return R.ok().put("data", jsonArray);
		}
		str = null;
		return R.ok().put("data", null);
		
			
	}
	
	//更新百度ip排除列表
	private int updateIpList(JSONObject ips) {
		
		String bodyStr = "{"+
				"\"header\":{" + 
				"\"token\":\"de86e485832d365067078dda4cd2d2eb\"," + 
				"\"accessToken\": \""+ user.getAccessToken() + 
				"\"}," + 
				"\"body\":{" + 
				"\"accountInfo\":" +
					  ips +
				"}}";
		//logger.info("测试服请求百度获取用户数据的请求包:"+bodyStr);
		
		data = getHttpJsonobject.httpsRequest(Constants.BAIDU_SEARCH_API+"/AccountService/updateAccountInfo", "POST", bodyStr);
		//logger.info("测试服请求百度获取json格式的用户数据:"+data);
		if ((data.getJSONObject("header").getString("desc")).equals("success")) {
			return 1;  //更新成功返回1
		}
		return 0; //更新失败返回0
		
	}
	
	//获取ip排除列表
	private List<String> getExcludeIpList(String domain) {
		List<ExcludeIpEntity> ipList = excludeIpService.getExcludeIp(domain);
		List<String> excludeIp = new ArrayList<>();
		for (int i = 0; i< ipList.size();i++) {
			excludeIp.add(ipList.get(i).getIp());
		}
		
		return excludeIp;
		
	}
	
	//返回IP所有所有数据
	private PageUtils getIpData(List<String> listStr, int page) {
		//分页显示
        perFirst = (page - 1) * 10;
		
        num = listStr.size();
		if (num % 10 == 0) {
        	for (index = perFirst; index < page * 10; index++) {
	         	jsonObject = JSONObject.parseObject(str.get(index));
	         	ipArea = exceptionOneWeekIpService.getIpLocation(jsonObject.getString("mip"));
	         	jsonObject.put("miparea", ipArea);
	         	ipOrNot = excludeIpOrNot(user.getUserDomain(), jsonObject.getString("mip"));
	         	if (ipOrNot == 1) {
	         		jsonObject.put("maddornot", "已添加");
				} else {
					jsonObject.put("maddornot", "未添加");
				}
	 			jsonArray.add(jsonObject);       	
	 		}
			pageUtil = new PageUtils(jsonArray, num, 10, page);
			str = null;
			return pageUtil;
		} else {
			if (page == (int)Math.ceil((double)num/10)) {
				int end = num % 10;
		        for (index = perFirst; index < page * 10 - (10 - end); index++) {
		         	jsonObject = JSONObject.parseObject(str.get(index));
		         	ipArea = exceptionOneWeekIpService.getIpLocation(jsonObject.getString("mip"));
		         	jsonObject.put("miparea", ipArea);
		         	logger.info("判断是否已经添加百度ip:"+excludeIpOrNot(user.getUserDomain(), jsonObject.getString("mip")));
		         	ipOrNot = excludeIpOrNot(user.getUserDomain(), jsonObject.getString("mip"));
		         	if (ipOrNot == 1) {
		         		jsonObject.put("maddornot", "已添加");
					} else {
						jsonObject.put("maddornot", "未添加");
					}
		 			jsonArray.add(jsonObject);       	
		 		}
		       
				pageUtil = new PageUtils(jsonArray, num, 10, page);
				str = null;
				return pageUtil;
			} else {

		        for (index = perFirst; index < page * 10; index++) {
		         	jsonObject = JSONObject.parseObject(str.get(index));
		         	ipArea = exceptionOneWeekIpService.getIpLocation(jsonObject.getString("mip"));
		         	jsonObject.put("miparea", ipArea);
		         	logger.info("查询是否已经添加百度ip排除列表：" + excludeIpOrNot(user.getUserDomain(), jsonObject.getString("mip")));
		         	ipOrNot = excludeIpOrNot(user.getUserDomain(), jsonObject.getString("mip"));
		         	if (ipOrNot == 1) {
		         		jsonObject.put("maddornot", "已添加");
					} else {
						jsonObject.put("maddornot", "未添加");
					}
		 			jsonArray.add(jsonObject);       	
		 		}
				pageUtil = new PageUtils(jsonArray, num, 10, page);
				str = null;
				return pageUtil;
			}		
		}
	}
	
	//测试获取ip排除列表
	@GetMapping("/getexcludeip")
	public List<String> getExcludeIp(String domain) {
		List<ExcludeIpEntity> ipList = excludeIpService.getExcludeIp(user.getUserDomain());
		List<String> excludeIp = new ArrayList<>();
		for (int i = 0; i< ipList.size();i++) {
			excludeIp.add(ipList.get(i).getIp());
		}
		
		return excludeIp;
		
	}
	
	
	//判断ip是否已经在百度ip排除列表
	public int excludeIpOrNot(String domain, String ip) {
		List<ExcludeIpEntity> ipList = excludeIpService.getExcludeIp(domain);
		
		for (int i = 0; i< ipList.size();i++) {
			if(ip.equals(ipList.get(i).getIp())) {
				return 1;
			} 
		}
		return 0;
	}
	
	//从session中获取用户信息
	private void getBdUserInfo(HttpServletRequest request) {
		user.setAccessToken(request.getSession().getAttribute("cur_accessToken").toString());
		user.setUsername(request.getSession().getAttribute("cur_username").toString());
		user.setUserDomain(request.getSession().getAttribute("cur_domain").toString());
		user.setUserId(request.getSession().getAttribute("cur_userId").toString());
//		logger.info("session中的domain和userId:"+user.getUserDomain()+":::"+user.getUserId());
	}
	

	
}
